# @Time : 2020/6/25 10:32
# @Author : Fioman 
# @Phone : 13149920693

a = dict(one=1, two=2, three=3)
b = {'one': 1, 'two': 2, 'three': 3}
c = dict(zip(["one", "two", "three"], [1, 2, 3]))
d = dict([('two', 2), ('one', 1), ('three', 3)])
e = dict({'three': 3, 'one': 1, 'two': 2})

print(a == b)
print(b == c)
print(c == d)
print(d == e)
print(a == b == c)
print(a == b == c == d == e)

# 字典推导式
DIAL_CODES = [(86, 'China'), (91, 'India'), (1, 'United States'), (62, 'Indonesia'), (55, 'Brazil'),
              (92, 'Pakistan'), (880, 'Bangladesh'), (234, 'Nigeria'), (7, 'Russia'), (81, 'Japan')]

country_code = {country: code for code, country in DIAL_CODES}
print("country_code = {}".format(country_code))

upper = {code: country.upper() for country, code in country_code.items() if code < 66}
print("upper = {}".format(upper))

# 使用setdefault 处理找不到的键
"""
当字典d[k]不能找到正确的键的时候,Python会抛出异常,这个行为符合Python所信奉的""
"""
import sys
import re

WORD_RE = re.compile(r"\w+")

index = {}

with open("test.txt",encoding='utf-8') as fp:
    for line_no,line in enumerate(fp,1):
        for match in WORD_RE.finditer(line):
            word = match.group()
            column_no = match.start() + 1
            location = (line_no,column_no)
            # 提取word出现的情况狂,如果没有它的记录,返回[]
            # 把单次新出现的位置添加到列表的后面
            # 把新的列表放回字典中,这又牵扯到一次查询操作
            occurrences = index.get(word,[])
            occurrences.append(location)
            index[word] = occurrences

for word in sorted(index,key=str.upper):
    print(word,index[word])


# 我们可以使用setdefault()只要用一行就解决了这个问题
index_2 = {}
with open("test.txt",encoding='utf-8') as fp:
    for line_no,line in enumerate(fp,1):
        for match in WORD_RE.finditer(line):
            word = match.group()
            column_no = match.start() + 1
            location = (line_no,column_no)
            index.setdefault(word,[]).append(location)

for word in sorted(index,key=str.upper):
    print(word,index[word])

my_dict = {}
my_dict.setdefault("a",[]).append(123) # 这么写的意思,和下面的意思是相同的

if "a" not in my_dict:
    my_dict["a"] = []
my_dict["a"].append(123)




































